package com.toolbox.controller;

import com.toolbox.service.ToolService;
import com.toolbox.service.PhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.io.ByteArrayOutputStream;

@RestController
@RequestMapping("/api/tools/photo")
public class PhotoController {

    @Autowired
    private ToolService toolService;
    
    @Autowired
    private PhotoService photoService;

    /**
     * 证件照背景更换接口
     * @param file 上传的照片文件
     * @param backgroundColor 目标背景颜色
     * @return 处理后的照片
     */
    @PostMapping("/background")
    public ResponseEntity<byte[]> changePhotoBackground(
            @RequestParam("file") MultipartFile file,
            @RequestParam("backgroundColor") String backgroundColor) {
        
        try {
            // 参数验证
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("照片不能为空".getBytes());
            }
            
            if (backgroundColor == null || backgroundColor.isEmpty()) {
                return ResponseEntity.badRequest().body("背景颜色不能为空".getBytes());
            }
            
            // 验证背景颜色是否支持
            if (!backgroundColor.equals("red") && !backgroundColor.equals("white") && !backgroundColor.equals("blue")) {
                return ResponseEntity.badRequest().body("不支持的背景颜色，仅支持red、white、blue".getBytes());
            }
            
            // 调用服务层进行处理
            byte[] processedData = toolService.changePhotoBackground(file, backgroundColor);
            
            // 生成响应头
            HttpHeaders headers = new HttpHeaders();
            String originalFileName = file.getOriginalFilename();
            String fileNameWithoutExt = originalFileName != null ? 
                    originalFileName.substring(0, originalFileName.lastIndexOf('.')) : "processed";
            String newFileName = fileNameWithoutExt + "_" + backgroundColor + "_background.jpg";
            
            // 设置响应头 - 处理中文文件名编码问题
            headers.setContentType(MediaType.IMAGE_JPEG);
            try {
                // 按照RFC 5987标准编码中文文件名
                String encodedFileName = java.net.URLEncoder.encode(newFileName, "UTF-8")
                        .replace("+", "%");
                headers.add("Content-Disposition", 
                        "attachment; filename*=UTF-8''" + encodedFileName);
            } catch (Exception e) {
                // 编码失败时使用默认文件名
                headers.setContentDispositionFormData("attachment", "processed_photo.jpg");
            }
            headers.setContentLength(processedData.length);
            
            return new ResponseEntity<>(processedData, headers, HttpStatus.OK);
            
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("照片处理失败".getBytes());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("处理失败".getBytes());
        }
    }
    
    /**
     * 更换证件照背景颜色（扩展版）
     * @param file 上传的照片文件
     * @param backgroundColor 目标背景颜色
     * @return 处理后的照片
     */
    @PostMapping("/background/batch")
    public ResponseEntity<byte[]> batchChangePhotoBackground(
            @RequestParam("file") MultipartFile file,
            @RequestParam("backgroundColor") String backgroundColor) {
        
        try {
            // 参数验证
            if (file.isEmpty()) {
                return ResponseEntity.badRequest().body("照片不能为空".getBytes());
            }
            
            if (backgroundColor == null || backgroundColor.isEmpty()) {
                return ResponseEntity.badRequest().body("背景颜色不能为空".getBytes());
            }
            
            // 调用服务层进行处理
            InputStream processedStream = photoService.changePhotoBackground2(file, backgroundColor);
            java.io.ByteArrayOutputStream buffer = new java.io.ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[1024];
            while ((nRead = processedStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            buffer.flush();
            byte[] processedData = buffer.toByteArray();
            processedStream.close();
            buffer.close();
            
            // 生成响应头
            HttpHeaders headers = new HttpHeaders();
            String originalFileName = file.getOriginalFilename();
            String fileNameWithoutExt = originalFileName != null ? 
                    originalFileName.substring(0, originalFileName.lastIndexOf('.')) : "processed"; 
            String newFileName = fileNameWithoutExt + "_" + backgroundColor + "_background.jpg";
            
            // 设置响应头 - 处理中文文件名编码问题
            headers.setContentType(MediaType.IMAGE_JPEG);
            try {
                // 按照RFC 5987标准编码中文文件名
                String encodedFileName = java.net.URLEncoder.encode(newFileName, "UTF-8")
                        .replace("+", "%");
                headers.add("Content-Disposition", 
                        "attachment; filename*=UTF-8''" + encodedFileName);
            } catch (Exception e) {
                // 编码失败时使用默认文件名
                headers.setContentDispositionFormData("attachment", "processed_photo.jpg");
            }
            headers.setContentLength(processedData.length);
            
            return new ResponseEntity<>(processedData, headers, HttpStatus.OK);
            
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage().getBytes());
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("照片处理失败".getBytes());
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("处理失败".getBytes());
        }
    }
}